package com.lzb.browser.adapter;

import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.Utils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.provider.BaseItemProvider;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.lzb.browser.R;
import com.lzb.browser.basic.ProviderMultiAdapter;
import com.lzb.browser.bean.RecordBean;
import com.lzb.browser.utils.IconDownloadTask;
import com.lzb.browser.utils.IconUtils;

public class RecordAdapter extends ProviderMultiAdapter<RecordBean> {


    public RecordAdapter() {
        addItemProvider(new RecordProvider());
    }

    private class RecordProvider extends BaseItemProvider<RecordBean> {
        @Override
        public int getItemViewType() {
            return ProviderMultiAdapter.TYPE_VIEW;
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_record;
        }

        @Override
        public void convert(@NonNull BaseViewHolder baseViewHolder, RecordBean bean) {
            baseViewHolder.setText(R.id.tvRecordItemTitle, bean.getTitle());
            baseViewHolder.setText(R.id.tvRecordItemUrl, bean.getUrl());

            ImageView ivIcon = baseViewHolder.getView(R.id.ivRecordItemIcon);

            // 加载图标
            loadIcon(ivIcon, bean);
        }
    }

    /**
     * 加载图标
     */
    private void loadIcon(ImageView ivIcon, RecordBean item) {
        // 优先使用保存的图标数据
//        if (item.getIcon() != null) {
//            ivIcon.setImageBitmap(item.getIcon());
//            return;
//        }

        // 加载默认图标
        loadDefaultIcon(ivIcon, item.getUrl());
    }

    private void loadDefaultIcon(ImageView imageView, String url) {
        // 生成网站的首字母作为默认图标
        String domain = extractDomain(url);
        String firstChar = domain.isEmpty() ? "W" : domain.substring(0, 1).toUpperCase();

        // 这里可以创建一个带有首字母的默认图标
        // 暂时使用默认的网页图标
        imageView.setImageResource(R.drawable.jilu);
    }

    private String extractDomain(String url) {
        if (url == null || url.isEmpty()) {
            return "";
        }

        try {
            // 简单的域名提取逻辑
            String domain = url.replace("https://", "")
                    .replace("http://", "")
                    .replace("www.", "");

            int slashIndex = domain.indexOf("/");
            if (slashIndex != -1) {
                domain = domain.substring(0, slashIndex);
            }

            return domain;
        } catch (Exception e) {
            return "";
        }
    }
}